import { TableInfo } from "@/entities/tableInfo.entity";

/**
 * 创建列表文件
 * @param name 
 * @param data 
 */
const createPageListCode = (data: TableInfo) => {
    const { fieldInfoList = [], indexInfoList = [] } = data;
    //表名下划线转小驼峰
    const smallName = data.name.replace(/_(.)/g, (a: string, b: string) => `${b.toLocaleUpperCase()}`);

    //表名下划线转大驼峰
    const bigName = data.name.replace(/(?:^|_)(\w)/g, (_, c) => c.toUpperCase());

    let dataPropsStr = '';
    fieldInfoList.forEach(item => {
        const isNumber = ["tinyint", 'int', 'integer', 'smallint', 'mediumint', 'bigint', 'decimal', 'numeric'].indexOf(item.dataType as string) != -1;
        dataPropsStr += `
                ${item.smallHumpCode}${item.isNull ? "?" : ""}:${isNumber ? "number" : "string"};`

    })



    const str = `
        import {
        ActionType,
        DragSortTable,
        PageContainer,
        ProColumns,
    } from '@ant-design/pro-components';
    import { Button, Divider, message, Popconfirm } from 'antd';
    import React, { useRef, useState } from 'react';
    import EditModal from './components/EditModal';
    import { deleteApi, selectListApi, sortApi } from './services';
    import { DeleteOutlined, FormOutlined } from '@ant-design/icons';
    export type dataProps = {
        ${dataPropsStr}
    };
    const Page: React.FC<unknown> = () => {
        const [handleModalInfo, setHandleModalInfo] = useState<{ visible: boolean, id?: number }>({
            visible: false
        });
        
    
        const actionRef = useRef<ActionType>();
        const [dataSource, setDataSource] = useState<any[]>([])
        const deleteItem = async (id: number) => {
            const res = await deleteApi(id)
            if (res.code == 200) {
                message.success("删除成功")
                actionRef.current?.reload()
            }
        }
    
        const columns: ProColumns<any>[] = [
            {
    
                title: '日期',
                dataIndex: 'date',
                hideInTable:true,
                valueType:"dateRange"
            },
            {
                title: '排序',
                dataIndex: 'sortOrder',
                width: "70px",
                hideInForm: true,
                hideInSearch: true,
                render: (dom, rowData, index) => {
                    return (
                        <span className="customRender">{rowData.sortOrder}</span>
                    );
                },
    
            },
            {
                title: 'id',
                dataIndex: 'id',
                width: "60",
            },
            {
                title: '名称',
                dataIndex: 'name',
                width: "120px",
            },
            
            {
                title: '描述',
                dataIndex: 'comment',
                width: "100px",
                valueType: 'text',
            },
    
            {
                title: '状态',
                dataIndex: 'status',
                width: "70px",
                hideInSearch: true,
                valueEnum: {
                    0: { text: '禁用', status: 'Error' },
                    1: { text: '启用', status: 'Success' },
    
                },
    
            },
            {
                title: '创建时间',
                dataIndex: 'createdAt',
                width: "150px",
                hideInForm: true,
                hideInSearch: true,
    
            },
            {
                title: '更新时间',
                dataIndex: 'updatedAt',
                width: "150px",
                hideInForm: true,
                hideInSearch: true
    
            },
    
            {
                title: '操作',
                dataIndex: 'option',
                width: "70px",
                valueType: 'option',
                render: (_, record) => (
                    <>
                        <FormOutlined className='e_icon' onClick={() => {
                            setHandleModalInfo({
                                visible: true,
                                id: record.id
                            })
                        }} />
    
                        <Divider type="vertical" />
                        <Popconfirm
                            title="删除"
                            description="确定删除当前分类？"
                            onConfirm={() => { deleteItem(record.id) }}
                        >
                            <DeleteOutlined className='d_icon' />
                        </Popconfirm>
                    </>
                ),
            },
        ];
    
        const handleDragSortEnd3 = (
            beforeIndex: number,
            afterIndex: number,
            newDataSource: any,
        ) => {
            setDataSource(newDataSource)
        };
    
    
        const sortClick = async () => {
            const res = await sortApi(dataSource.map((item, i) => { return { id: item.id, sortOrder: i + 1 } }))
            if (res.code == 200) {
                message.success('修改列表排序成功');
                actionRef.current?.reload()
            }
        }
    
        const scrollX = columns.reduce((pre, next) => {
            return pre + parseInt(next.width + "")
        }, 0)
    
        return (
            <PageContainer
                header={{
                    title: '${data.comment}',
                }}
            >
                <DragSortTable<any>
                    headerTitle="查询表格"
                    actionRef={actionRef}
                    rowKey="id"
                    search={{
                        labelWidth: 120,
                    }}
                    toolBarRender={() => [
                        <Button
                            key="soort"
                            type="primary"
                            onClick={sortClick}
                        >
                            排序
                        </Button>,
                        <Button
                            key="1"
                            type="primary"
                            onClick={() => setHandleModalInfo({ visible: true })}
                        >
                            新建
                        </Button>,
                    ]}
                    dataSource={dataSource}
                    request={async (params, sorter, filter) => {
                        
                        let orderBy = 'id desc';
                        const objArr = Object.keys(sorter);
                        // 有排序字段,暂时支持单字段
                        if (objArr.length > 0) {
                            const file = objArr[0];
                            if (sorter[file] == "descend") {
                                orderBy = \`\${file} desc\`
                            } else {
                                orderBy = \`\${file} asc\`
                            }
                        }
    
                        const { current, pageSize, date,...other } = params
                        const { data, code } = await selectListApi({
                            page: current,
                            pageSize: pageSize,
                            orderBy,
                            fromDate:date?.[0]||undefined,
                            toDate:date?.[1]||undefined,
                            ...other
    
                        });
                        setDataSource(data.list)
                        return {
                            success: code == 200,
                            total: data.total || 0
                        };
                    }}
                    columns={columns}
                    pagination={{
                        pageSize: 10,
                        onChange: (page) => console.log(page),
                    }}
                    onDragSortEnd={handleDragSortEnd3}
                    dragSortKey="sortOrder"
    
                    scroll={{
                        x: scrollX,
                    }}
                />
                <EditModal
                    id={handleModalInfo.id}
                    onCancel={() => { setHandleModalInfo({ visible: false }); actionRef.current?.reload() }}
                    modalVisible={handleModalInfo.visible}
                >
                </EditModal>
            </PageContainer>
        );
    };
    
    export default Page;
    
        
        
        `
    return str
}
export default createPageListCode